package com.uzai.console.service.rocketmq.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.common.dto.notice.AppNoticeDto;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.KefuSendMsgEnum;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.protoc.SendSmsReqProtoc;
import com.uzai.common.utils.MqTopics;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.orderreport.OrderReportDto;
import com.uzai.console.dto.rocketmq.configplan.BigPromotionDto;
import com.uzai.console.dto.rocketmq.configplan.ClientSetDto;
import com.uzai.console.dto.rocketmq.devicewechatinfo.CloseClientAppDto;
import com.uzai.console.dto.rocketmq.devicewechatinfo.UpdateClientAppDto;
import com.uzai.console.dto.rocketmq.friendrequest.AddUserApplyDto;
import com.uzai.console.dto.rocketmq.friendrequest.DeleteUserDto;
import com.uzai.console.dto.rocketmq.groupsendjob.GroupSendMsgDto;
import com.uzai.console.dto.rocketmq.pyq.PostSnsCommentDto;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.rocketmq.wxgroup.*;
import com.uzai.console.dto.rocketmq.wxpubuser.OrderMsgDto;
import com.uzai.console.dto.rocketmq.wxpubuser.WxpubMsg;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserConfigDto;
import com.uzai.console.mapper.WxpubUserMapper;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: liuqi
 * @Date: 2021/11/15 14:45
 * @Description:
 */
@Service
public class NoticeMsgPushProducerServiceImpl implements NoticeMsgPushProducerService {
    private static Logger logger = LoggerFactory.getLogger(NoticeMsgPushProducerServiceImpl.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate2; //报警消息
    @Autowired
    private WxpubUserMapper wxpubUserMapper;

    private static final int TOTAL_RETRY = 2;

    /**
     * 发送普通消息
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    @Override
    public void sendMessage(MsgDto<NoticeMsgDto> msgDto) {

        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        String topic = MqTopics.USER_TOPIC;
        //公众号会员，则单独走一个topic
        if(Tools.getInteger(msgDto.getDeviceType()).intValue() == DeviceTypeEnum.WX_PUB_VALUE){
            topic = MqTopics.WXPUB_MSG;
            WxpubMsg<OrderMsgDto> wxpubMsg = new WxpubMsg<>();
            wxpubMsg.setMsgType(0); //普通文字消息
            OrderMsgDto orderMsgDto = new OrderMsgDto();
            wxpubMsg.setMsg(orderMsgDto);
            NoticeMsgDto  noticeMsgDto = msgDto.getContent();
            if(noticeMsgDto != null){
                String bizUserId = noticeMsgDto.getBizUserId();
                WxpubUser wxpubUser = wxpubUserMapper.selectByBizUserId(bizUserId, msgDto.getMerId());
                if(wxpubUser != null){
                    orderMsgDto.setUserId(wxpubUser.getId());
                    orderMsgDto.setMsgContent(noticeMsgDto.getContent());
                    noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                }
            }
            msg = Tools.getStrEmpty(JSONObject.toJSONString(wxpubMsg));
            logger.info("--发送公众号会员普通消息--msg:{}",msg);
        }else{
            topic = MqTopics.USER_TOPIC;
            msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
            logger.info("--发送会员普通消息--msg:{}",msg);
        }

        //替换下
        String msgFinal = msg;
        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(topic , msgFinal, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--发送普通消息-成功--msg:{}",msgFinal);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--发送普通消息-失败--msg={}, error:{}", msgFinal, throwable.getMessage());
            }
        }, 3000);

    }

    /**
     * 发送App推送消息
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param appNoticeDto
     */
    @Override
    public void sendAppMessage(AppNoticeDto appNoticeDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(appNoticeDto));
        String topic =MqTopics.APP_NOTICE;
        logger.info("--调用发送App会员消息--msg:{}",msg);

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(topic , msg, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--发送App会员消息-成功--msg:{}",msg);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--发送App会员消息-失败--msg={}, error:{}", throwable.getMessage());
            }
        }, 3000);
    }

    /**
     * 通过好友申请消息
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    @Override
    public void addFriendRequest(MsgDto<AddUserApplyDto> msgDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--通过好友申请消息--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.PASS_ADD_USER_TOPIC , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                addFriendRequest(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 删除好友
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    @Override
    public void deleteUser(MsgDto<DeleteUserDto> msgDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--删除好友--msg:{}",msg);
        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.DEL_USER_TOPIC , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                deleteUser(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 同步微信通信录指令
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    @Override
    public void updateWxContacts(MsgDto<Object> msgDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--同步微信通信录指令--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.GET_MAIL_LIST , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                updateWxContacts(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 更新客户端指令
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    @Override
    public void updateClientApp(MsgDto<UpdateClientAppDto> msgDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--更新客户端指令--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.UPDATE_CLIENT_APP , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                updateClientApp(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }


    /**
     * 关闭客户端和微信指令
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    public void closeClientApp(MsgDto<CloseClientAppDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("---关闭客户端和微信指令-- msg:{}",msg);
        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.CLOSE_CLIENT_APP , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                closeClientApp(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 退出微信群指令
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    public void quitWxGroup(MsgDto<QuitGroupDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--发送退群指令-- msg:{}",msg);
        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.QUIT_GROUP , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                quitWxGroup(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }


    /**
     * 增加群发消息
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    public void groupSendMsg(GroupSendMsgDto msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--增加群发消息--msg:{}",msg);

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(MqTopics.GROUP_SEND , msg, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--增加群发消息-成功--msg:{}",msg);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--增加群发消息-失败--msg={}, error:{}", msg, throwable.getMessage());
            }
        }, 3000);
    }

    /**
     * 设置用户备注
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    public void setUserRemark(MsgDto<SetUserRemarkDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--设置用户备注--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.SET_USER_REMARK_TOPIC , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                setUserRemark(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 踢掉群成员
     * @author lucher
     * @date 2022/04/30 17:09
     * @param msgDto
     */
    public void kickGroupUser(MsgDto<KickGroupMemberDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--踢掉群成员--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.KICK_GROUP_USER , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                kickGroupUser(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 获取微信群成员
     * @author lucher
     * @date 2022/04/30 17:09
     * @param msgDto
     */
    public void getGroupMemberList(MsgDto<GetGroupMemberListDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--获取微信群成员--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.GET_GROUP_MEMBER_LIST , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                getGroupMemberList(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 添加微信群好友请求
     * @author lucher
     * @date 2022/04/30 17:09
     * @param msgDto
     */
    public void addFriendReq(MsgDto<AddFriendReqDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--个人微信添加微信群好友请求--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.ADD_FRIEND_REQ , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                addFriendReq(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 单独发送朋友圈评论
     * @author lucher
     * @date 2022/09/15 17:09
     * @param msgDto
     */
    public void sendPyqComment(MsgDto<PostSnsCommentDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--MQ发送朋友圈评论--msg:{}",msg);

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(MqTopics.SEND_PYQ_COMMENT , msg, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--MQ发送朋友圈评论-成功--msg:{}",msg);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--MQ发送朋友圈评论-失败--msg={}, error:{}", msg, throwable.getMessage());
            }
        }, 3000);
    }

    /**
     * 推送大促插件数据
     * @author lucher
     * @date 2022/09/15 17:09
     * @param msgDto
     */
    public void pushBigPromotion(MsgDto<BigPromotionDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--MQ推送大促插件数据--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.PUSH_CLIENT_SETTTING , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                pushBigPromotion(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 推送客户端设置插件数据
     * @author lucher
     * @date 2022/09/15 17:09
     * @param msgDto
     */
    public void pushClientSet(MsgDto<ClientSetDto> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--MQ推送客户端设置插件数据--msg:{}",msg);

        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.PUSH_CLIENT_SETTTING , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                pushClientSet(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 发送切换设备端指令
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    public void sendDeviceMsgHander(MsgDto msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--发送切换设备端指令-- msg:{}",msg);
        if (msgDto.getRetry() < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.IM_TO_MOBILE , msg, 3000);
            } catch (Exception e) {
                logger.error("err:", e);
                msgDto.setRetry(msgDto.getRetry() + 1);
                sendDeviceMsgHander(msgDto);
            }
        }else {
            logger.info("retry fail:{}",msg);
        }
    }

    /**
     * 发送请求话费余额指令
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param msgDto
     */
    public void sendQueryPhoneBal(MsgDto<SendSmsReqProtoc> msgDto){
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(msgDto));
        logger.info("--发送请求话费余额指令-- msg:{}",msg);

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(MqTopics.IM_TO_MOBILE , msg, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--发送请求话费余额指令-成功--msg:{}",msg);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--发送请求话费余额指令-失败--msg={}, error:{}", msg, throwable.getMessage());
            }
        }, 3000);

    }

    /**
     * 推送客服配置
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param kefuUserConfigDto
     */
    @Override
    public void chatappPushConfig(KefuUserConfigDto kefuUserConfigDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(kefuUserConfigDto));
        String topic =MqTopics.CHATAPP_PUSH_CONFIG;
        logger.info("--调用推送客服配置发送消息--msg:{}",msg);

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(topic , msg, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--调用推送客服配置发送消息-成功--msg:{}",msg);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--调用推送客服配置发送消息-失败--msg={}, error:{}", msg, throwable.getMessage());
            }
        }, 3000);
    }

    /**
     * 异步发送系统异常报警消息
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param alarmMsgFeignDto
     */
    @Override
    public void sendSysAlarmMsgAsync(AlarmMsgFeignDto alarmMsgFeignDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(alarmMsgFeignDto));
        String topic =MqTopics.BRO_SYS_MSG;
        logger.info("--MQ发送异常报警消息--msg:{}",msg);

        //异步调用MQ发送消息
        rocketMQTemplate2.asyncSend(topic , msg, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--MQ发送异常报警消息-成功--msg:{}",msg);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--MQ发送异常报警消息-失败--msg={}, error:{}", msg, throwable.getMessage());
            }
        }, 3000);
    }

    /**
     * 异步订单统计数据消息
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param orderReportDto
     */
    @Override
    public void sendOrderReportAsync(OrderReportDto orderReportDto) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(orderReportDto));
        String topic =MqTopics.USER_EXT_CHANGE;
        logger.info("--MQ发送订单统计数据--msg:{}",msg);

        //异步调用MQ发送消息
        rocketMQTemplate2.asyncSend(topic , msg, new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("--MQ发送订单统计数据-成功--msg:{}",msg);
            }

            @Override
            public void onException(Throwable throwable) {
                logger.error("--MQ发送订单统计数据-失败--msg={}, error:{}", msg, throwable.getMessage());
            }
        }, 3000);
    }

}
